var criteriaLevel2Id = db.CriteriaLevel2.findOne({ Name: "Product Involvement"})._id;
var template = 
    db.TemplateCriteria.aggregate([
  { "$lookup": {
    "localField": "CriteriaLevel3Id",
    "from": "CriteriaLevel3",
    "foreignField": "_id",
    "as": "orderinfo"
  } },
  {$match : {CriteriaLevel2Id:criteriaLevel2Id}},
  { "$unwind": "$orderinfo" },
  { "$project": {
    "_id": 1,
    "orderinfo.Name": 1,
    "CriteriaEntityField":2
  } },
  {$sort:{"orderinfo.Name": 1}}
])
var names = [];

var idx=1;
var criterialevel3id = "";
template.forEach(function (tpl)
{
    var category =tpl.CriteriaEntityField.split(" ")[1]; 
    var data = tpl.CriteriaEntityField.replace(category + " ", "");
    data = data.replace(data.split(" ")[0]+ " ", "");

	names.push({key:  parseInt(category.substring(2, category.length)), 
                    value : tpl.CriteriaEntityField, 
                    id: tpl._id,
                    name:tpl.orderinfo.Name, 
                    order: 0,
                    dp:data
                    })
   
    });

print(names)

names.sort(function (item1,item2) {
  if (item1.name > item2.name) return 1;
  if (item1.name < item2.name) return -1;
  
  if (item1.key > item2.key) return 1;
  if (item1.key < item2.key) return -1;
    
  if (item1.dp > item2.dp) return 1;
  if (item1.dp < item2.dp) return -1;

});

names.forEach(function (item)
{
      db.TemplateCriteria.update({_id:item.id},{$set: {Order:idx++}})
    })




    
   